import java.io.*;
import java.net.*;

public class ClientHandler implements Runnable {
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    private String username;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            // 初始化输入输出流
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            // 处理登录
            while (true) {
                out.println("USERNAME_REQUEST");
                username = in.readLine();

                out.println("PASSWORD_REQUEST");
                String password = in.readLine();

                if (DBConnection.validateUser(username, password)) {
                    out.println("LOGIN_SUCCESS");
                    DBConnection.updateOnlineStatus(username, true);
                    ChatServer.updateUserList();
                    ChatServer.broadcast(username + " has joined the chat!", this);
                    break;
                } else {
                    out.println("LOGIN_FAILURE");
                }
            }

            // 处理消息
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                if (inputLine.equals("LOGOUT")) {
                    break;
                }
                ChatServer.broadcast(username + ": " + inputLine, this);
            }

            // 客户端退出处理
            out.println("LOGOUT_ACK");
            ChatServer.broadcast(username + " has left the chat.", this);
            DBConnection.updateOnlineStatus(username, false);
            ChatServer.removeClient(this);

        } catch (IOException e) {
            System.out.println("Error in ClientHandler: " + e.getMessage());
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 发送消息给客户端
    public void sendMessage(String message) {
        out.println(message);
    }

    // 获取用户名
    public String getUsername() {
        return username;
    }
}
